const Koa = require('koa');
const Router = require('koa-router');
const static = require('./routers/static');
const path = require('path');
const body = require('koa-better-body');
const session = require('koa-session');
const fs = require('fs');
const ejs = require('koa-ejs');
const config = require('./config');
const cors = require('koa2-cors');
let server = new Koa();
server.listen(config.PORT);
console.log(`server running at ${config.PORT}`);

//中间件
server.use(body({
    uploadDir: config.UPLOAD_DIR
}));
server.keys=fs.readFileSync('.keys').toString().split('\n');
server.use(session({
    maxAge: 20*60*1000,
    renew: true
},server));
//数据库
server.context.db = require('./libs/database');
server.context.config = config;
let router = new Router();
//渲染
ejs(server,{
    root: path.resolve(__dirname,'template'),
    layout: false,
    viewExt: 'ejs',
    cache: false,
    debug: false
});
server.use(async (ctx,next)=>{
    let {HTTP_ROOT} = ctx.config;
    try{
        await next();
        if(!ctx.body){
            await ctx.render('/www/404',{
                HTTP_ROOT
            })
        }
    }catch(err){
        await ctx.render('/www/404',{
            HTTP_ROOT
        })
    }
})
//统一处理
// router.use(async(ctx, next)=>{
//     try{
//         await next();
//     }catch(e){
//         ctx.throw(500, 'Internal Server Error');
//     }
// });
router.use('/admin', require('./routers/admin'));
router.use('/api', require('./routers/api'));
router.use('/', require('./routers/www'));
// static(router,{
//     html: 365  //html缓存365天
// });
server.use(cors({
  /*  origin: function(ctx) { //设置允许来自指定域名请求
        if (ctx.url === '/get') {
            return '*'; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
    },*/
    maxAge: 100, //指定本次预检请求的有效期，单位为秒
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    //设置服务器支持的所有头信息字段
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'],
    credentials: true, //是否允许发送Cookie
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'], //设置获取其他自定义字段
}));
static(router);
server.use(router.routes());